﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml;


namespace YTSK.cSK.UKey
{
    public class cKP_DZP
    {
        #region DLL

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(IntPtr hWnd, ref cDll.RECT lpRect);

        #endregion

        public static string proc(Model.SK_SalebillVouch sk, string filePath, out string fpdm, out string fphm,
            string str_xml)
        {
            var err = "";
            fpdm = "";
            fphm = "";

            #region 清空待开票目录下的xml文件（避免错开票）

            // DirectoryInfo info = new DirectoryInfo(@"C:\税控接口\待开票\");
            // FileInfo[] fileInfos = info.GetFiles("*.xml").Where(s => s.Extension == ".xml").ToArray();
            // foreach (var fileInfo in fileInfos)
            // {
            //     fileInfo.Attributes = FileAttributes.Normal;
            //     File.Delete(fileInfo.FullName);
            // }

            #endregion

            #region 保存导入文件

            var destpath = "C:\\税控接口\\待开票\\"; //待开票目标文件夹-广州/上海
            // var destpath = "E:\\税控uk\\导入文件目录\\"; //待开票目标文件夹-深圳
            #region 清空待开票目录下的xml文件（避免错开票）

            DirectoryInfo info = new DirectoryInfo(destpath);
            FileInfo[] fileInfos = info.GetFiles("*.xml").Where(s => s.Extension == ".xml").ToArray();
            foreach (var fileInfo in fileInfos)
            {
                fileInfo.Attributes = FileAttributes.Normal;
                File.Delete(fileInfo.FullName);
            }

            #endregion
            var destfile = $"{destpath}{sk.cCode}.xml";
            var xml = new XmlDocument();
            xml.LoadXml(str_xml);
            xml.Save(destfile);

            #endregion
            

            // IntPtr hWnd = cDll.FindWindow(null, "增值税发票开票软件（税务UKey版）"); //获取新开票句柄
            // if (hWnd.ToInt32() == 0)
            // {
            //     err = $"没有找到[增值税发票开票软件（税务UKey版）]窗口或者系统运行速度太慢，请与系统管理员联系";
            //     return err;
            // }
            var l_win = cDllExt.GetAllChild(IntPtr.Zero);
            var l_win_tmp = l_win.Where(s => s.text == "增值税发票开票软件（税务UKey版）").ToList();
            var tmp_win = l_win_tmp.FirstOrDefault(s =>
                s.position.Width - s.position.Left > 950 && s.position.Height - s.position.Top > 700);
            if (tmp_win == null)
            {
                err = $"没有找到[增值税发票开票软件（税务UKey版）]窗口或者系统运行速度太慢，请与系统管理员联系";
                return err;
            }

            var hWnd = tmp_win.hwnd;
            cDll.SetForegroundWindow(hWnd); //设置为活动窗口
            cDll.ShowWindow(hWnd, 1); //展示最小化后台的窗口（SetForegroundWindow不能），并初始化为正常大小
            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt() * 3);
            cDll.RECT rectSrc = new cDll.RECT();
            GetWindowRect(hWnd, ref rectSrc);
            int widthSrc = rectSrc.Right - rectSrc.Left; //窗口的宽度
            int heightSrc = rectSrc.Bottom - rectSrc.Top; //窗口的高度
            int xSrc = rectSrc.Left;
            int ySrc = rectSrc.Top;
            double threshold = 0.0;
            int icountSrc = 0;
            do
            {
                cDll.SetForegroundWindow(hWnd);
                cDll.ShowWindow(hWnd, 1); //展示最小化后台的窗口（SetForegroundWindow不能），并初始化为正常大小
                Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt());
                var imgSrc = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc);
                var dppbmp = Properties.Resources.dzzp_ukey;
                var dppPoint = Common.HandleImg.FindPicFromImage(imgSrc, dppbmp);
                cDll.SetCursorPos(dppPoint.X, dppPoint.Y);
                var wtdpp = dppbmp.Width;
                var htdpp = dppbmp.Height;
                var dppCut = Common.HandleImg.GetScreenImg(xSrc + dppPoint.X, ySrc + dppPoint.Y, wtdpp, htdpp);
                threshold = Common.HandleImg.MatchPicBySift(dppbmp, dppCut);
                icountSrc++;
            } while (threshold < 0.9 && icountSrc < 10);

            if (threshold < 0.9)
            {
                err = "这不是电子发票，请正确使用发票填开！";
                return err;
            }

            cDll.RECT rectSrc1 = new cDll.RECT();
            GetWindowRect(hWnd, ref rectSrc1);
            int widthSrc1 = rectSrc1.Right - rectSrc1.Left; //窗口的宽度
            int heightSrc1 = rectSrc1.Bottom - rectSrc1.Top; //窗口的高度
            int xSrc1 = rectSrc1.Left;
            int ySrc1 = rectSrc1.Top;
            var imgSrc1 = Common.HandleImg.GetScreenImg(xSrc1, ySrc1, widthSrc1, heightSrc1);
            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt() * 3);

            int icount = 0;
            do
            {
                Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt());
                var fpdmbmp = Properties.Resources.fpdm_ukey_dpp; //定位
                var fpdmbmpNO = Properties.Resources.fpdm_ukey_dpp_NO; //需要回写的数字，主要用来获取需要截取的尺寸
                var fpdmPoint = Common.HandleImg.FindPicFromImage(imgSrc1, fpdmbmp); //获取坐标
                var wtfpdm = fpdmbmpNO.Width;
                var htfpdm = fpdmbmpNO.Height;
                var fpdmCut =
                    Common.HandleImg.GetScreenImg(xSrc1 + fpdmPoint.X + 60, ySrc1 + fpdmPoint.Y, wtfpdm + 15, htfpdm);
                fpdmCut = Common.HandleImg.PicProcess(fpdmCut);
                var orcResultfpdm = Common.HandleImg.Reconize(OcrType.发票代码, fpdmCut);
                var matchfpdm = System.Text.RegularExpressions.Regex.Match(orcResultfpdm, "\\d{10,12}");
                // var reconizePaddle= Common.HandleImg.ReconizePaddle(fpdmCut);
                // if (reconizePaddle.confidence > 0.9)
                // {
                //     if (matchfpdm.Value.ObjToString() == reconizePaddle.text.ObjToString())
                //     {
                //         fpdm = matchfpdm.Value;
                //     }
                //     else
                //     {
                //         fpdm = reconizePaddle.text;
                //     }
                // }
                // else
                // {
                //     fpdm = matchfpdm.Value;
                // }
                
                fpdm = matchfpdm.Value;
                
                var fphmbmp = Properties.Resources.fphm_ukey_dpp; //定位
                var fphmbmpNO = Properties.Resources.fphm_ukey_dpp_NO; //需要回写的数字，主要用来获取需要截取的尺寸
                var fphmPoint = Common.HandleImg.FindPicFromImage(imgSrc1, fphmbmp); //获取坐标
                var wtfphm = fphmbmpNO.Width;
                var htfphm = fphmbmpNO.Height;
                var fphmCut =
                    Common.HandleImg.GetScreenImg(xSrc1 + fphmPoint.X + 60, ySrc1 + fphmPoint.Y, wtfphm, htfphm);
                fphmCut = Common.HandleImg.PicProcess(fphmCut);
                var orcResultfphm = Common.HandleImg.Reconize(OcrType.发票号码, fphmCut);
                var matchfphm = System.Text.RegularExpressions.Regex.Match(orcResultfphm, "\\d{8}");
                fphm = matchfphm.Value;
                icount++;
            } while ((fpdm.ObjToString().Length == 0 || fphm.ObjToString().Length == 0) && icount < 10);

            var dppStart = Properties.Resources.start_ukey; //开始按钮
            var startPoint = Common.HandleImg.FindPicFromImage(imgSrc1, dppStart);
            var wtStart = dppStart.Width;
            var htStart = dppStart.Height;
            var xOfsStart = wtStart * 1 / 2;
            var yOfsStart = htStart * 1 / 2;
            var clickSubx = rectSrc1.Left + startPoint.X + xOfsStart;
            var clickSuby = rectSrc1.Top + startPoint.Y + yOfsStart;
            cDllExt.mouseClick(clickSubx, clickSuby);
            
            return "";
        }
    }
}